package com.why.serviceorder.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.why.commonresults.Result;
import com.why.serviceorder.bean.TOrder;
import com.why.serviceorder.service.TOrderService;
import com.why.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author why
 * @since 2021-02-22
 */
@RestController
@RequestMapping("/serviceorder")
@CrossOrigin
public class TOrderController {

    @Autowired
    private TOrderService orderService;

    /**
     * 创建订单
     *
     * @param courseId
     * @param request
     * @return
     */
    @GetMapping("/createOrder/{courseId}")
    public Result createOrder(@PathVariable("courseId") String courseId,
                              HttpServletRequest request
    ) {

        //从请求头中获取用户的id
        String userId = JwtUtils.getMemberIdByJwtToken(request);

        String order = orderService.createOrderByCourseId(userId, courseId);
        System.out.println("订单号为" + order);
        return Result.ok().data("orderNo", order);
    }

    /**
     * 订单号查询订单
     *
     * @param orderNo
     * @return
     */

    @GetMapping("/getOrder/{orderNo}")
    public Result getOrder(@PathVariable("orderNo") String orderNo) {
        System.out.println(orderNo);
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderNo);
        TOrder order = orderService.getOne(wrapper);
        System.out.println(order);
        return Result.ok().data("order", order);
    }

    /**
     * 根据用户id和课程id来确定当前课程是否被支付
     * 应该进行一波是否登录的判断
     */

    @GetMapping("isBuyCourse/{memberid}/{id}")
    public boolean isBuyCourse(@PathVariable String memberid,
                               @PathVariable String id) {
        System.out.println(memberid+"\t"+id);
//订单状态是1表示支付成功
        int count = orderService.count(new QueryWrapper<TOrder>().eq("member_id",
                memberid).eq("course_id", id).eq("status", 1));
        if(count>0) {
            return true;
        } else {
            return false;
        }
    }


}

